<?php
class Zend_View_Helper_MyJavaScript extends Zend_View_Helper_HeadScript{

	public function MyJavaScript()
	{
		//<script type="text/javascript" src="public/js/index/index.js"></script>
		$items = array();
		$scripts = array();
		$files=array();
		$name='new';
		foreach ($this as $item) {
			if ($item->type == 'text/javascript' ){
				$scripts[$item->attributes['src']][] = $item->attributes['src'];
				if(!empty($item->attributes['jsmini']) &&  $item->attributes['jsmini'] == true){
					$scripts[$item->attributes['src']]['jsmini'] =true;
				}
			} else {
				$items[] = $this->itemToString($item, '', '', '');
			}
		}
		$i=0;
		foreach ($scripts as $src=>$js) {
			$item = new stdClass();
			$item->type = 'text/javascript';
			$name.=$src;
			$files[$i]['src']=$src;
			if(!empty($js['jsmini']) &&  $js['jsmini'] == true){
				$files[$i]['jsmini']=$js['jsmini'];
			}
			$i++;
		}
		$newname = 'js_' . md5('vcss'  . $name) . '.js';
		$this->process($files, $newname);
		$item->attributes['src'] = $this->getMinUrl() . '/' . $newname;
		$items[] =   $this->itemToString($item, '', '', '');
		
		return implode($this->_escape($this->getSeparator()), $items);
		
	}

	protected function process($files, $name)
	{
		$cacheFile = $this->getDir() . '/' . $name;
		if (file_exists($cacheFile) ) {
			$data = filemtime($cacheFile)+3600;
			if(($data < time())){
				return;
			}
		}
		$cache='';
		foreach ($files as $v) {
			if(!empty($v['jsmini']) &&  $v['jsmini'] == true){
				$cache .=Application_Model_JsMinifier::minify(file_get_contents($this->jsDir(). $v['src'] ));
			}
			else{
				$cache .=(file_get_contents($this->jsDir(). $v['src'] ));
			}
		}
		$fp = fopen($cacheFile, "wb");
		if ($fp) {
			fwrite($fp, $cache);
			fclose($fp);
		}
	}

	public function getMinUrl() {

		return  BASE_URL.'/tmp';
	}
	protected function jsDir(){
		return realpath(APPLICATION_PATH ."/../")."/";
	}
	
	public function getDir(){
		return APPLICATION_PATH."/../public/tmp";
	}

}
